from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime

db = SQLAlchemy()

class Student(db.Model):
    __tablename__ = 'students'
    id = db.Column(db.Integer, primary_key=True)
    student_id = db.Column(db.String(64), unique=True, nullable=False)
    name = db.Column(db.String(128), nullable=False)
    class_name = db.Column(db.String(64))
    grades = db.relationship('Grade', back_populates='student', cascade='all, delete-orphan')

    def __repr__(self):
        return f'<Student {self.student_id} - {self.name}>'

class Course(db.Model):
    __tablename__ = 'courses'
    id = db.Column(db.Integer, primary_key=True)
    course_code = db.Column(db.String(64), unique=True, nullable=False)
    name = db.Column(db.String(128), nullable=False)
    credit = db.Column(db.Float)
    grades = db.relationship('Grade', back_populates='course', cascade='all, delete-orphan')

    def __repr__(self):
        return f'<Course {self.course_code} - {self.name}>'

class Grade(db.Model):
    __tablename__ = 'grades'
    id = db.Column(db.Integer, primary_key=True)
    student_id = db.Column(db.Integer, db.ForeignKey('students.id'), nullable=False)
    course_id = db.Column(db.Integer, db.ForeignKey('courses.id'), nullable=False)
    score = db.Column(db.Float, nullable=False)
    grade_status = db.Column(db.String(32))
    timestamp = db.Column(db.DateTime, default=datetime.utcnow)

    student = db.relationship('Student', back_populates='grades')
    course = db.relationship('Course', back_populates='grades')

    __table_args__ = (
        db.UniqueConstraint('student_id', 'course_id', name='_student_course_uc'),
    )

    def __repr__(self):
        return f'<Grade Student:{self.student_id} Course:{self.course_id} Score:{self.score}>'
